<template>
  <div>
    <el-row type="flex" align="middle" justify="left" v-show="edit">
      <el-form inline>
        <!-- <el-form-item label>
          <el-cascader filterable size="mini" placeholder="请先选择投放区域" :options="addressArray" clearable :change-on-select="true" v-model="addressForm.regionValue" @change="handleAddrChange" @active-item-change="handleAddrItemChange" :props="addressProps"></el-cascader>
        </el-form-item> -->
        <el-form-item label>
          <el-input show-word-limit maxlength="50" size="mini" v-model="addressForm.address" placeholder="设备安装地址" id="input" style="width:400px"></el-input>
        </el-form-item>
        <el-form-item label>
          <el-button size="mini" @click="handleSearch" type="primary">搜索</el-button>
        </el-form-item>
        <el-form-item label>
          <el-button @click="savePlace" type="warning" size="mini">保存</el-button>
        </el-form-item>
        <el-form-item label>
          <el-button @click="cancel" type="info" size="mini">取消</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row v-if="edit">
      <div id="js-result" v-show="false" class="result"></div>
    </el-row>
    <el-row style="width:100%" :style="{height:height+'px'}">
      <div id="js-container" style="width:100%;height:100%;">正在加载数据 ...</div>
    </el-row>
  </div>
</template>
<script>
export default {
  name: 'myMap',
  props: {
    height: {
      Type: Number,
      default: 300
    },
    lat: {
      type: Number,
      // default: '22.636733'
      default: 22.636733
    },
    lng: {
      type: Number,
      // default: '114.024459'
      default: 114.024459
    },
    edit: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    edit: {
      handler: function (val, oldVal) {
        if (!val && this.placeSearch) {
          this.placeSearch.clear()
        }
      },
      immediate: true
    },
    lng: {
      handler: function (val, oldVal) {
        if (this.map) {
          this.map.setCenter([val, this.lat])
          this.map.remove(this.marker)
          this.addOriginMarker(val, this.lat)
        }
      },
      immediate: true
    },
    lat: {
      handler: function (val, oldVal) {
        if (this.map) {
          this.map.setCenter([this.lng, val])
          this.map.remove(this.marker)
          this.addOriginMarker(this.lng, val)
        }
      },
      immediate: true
    }
  },
  data () {
    return {
      submitAddress: '',
      marker: {},
      standardPlace: '',
      positionPicker: undefined,
      map: undefined,
      addressForm: {
        cityCode: undefined,
        id: null,
        regionValue: [],
        address: null,
        coordinate: {
          latitude: '',
          longitude: ''
        }
      },
      addressArray: [],
      addressProps: {
        label: 'cityNameZh',
        value: 'id',
        children: 'children'
      },
      placeIdNameMap: {},
      searchKey: '',
      placeSearch: null,
      dragStatus: false,
      AMapUI: null,
      AMap: null,
      place: {
        address: '',
        lat: '',
        lng: ''
      }
    }
  },
  methods: {
    cancel () {
      this.map.setCenter([this.lng, this.lat])
      this.$emit('cancel')
    },
    savePlace () {
      this.addressForm.address = this.submitAddress
      this.$emit('save-place', this.addressForm)
    },
    // 搜索
    handleSearch () {
      this.placeSearch.search(this.addressForm.address)
    },
    // 实例化地图
    initMap () {
      // 加载PositionPicker，loadUI的路径参数为模块名中 'ui/' 之后的部分
      const AMapUI = (this.AMapUI = window.AMapUI)
      const AMap = (this.AMap = window.AMap)
      AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
        const mapConfig = {
          zoom: 16,
          cityName: '绵阳'
        }
        if (this.lat && this.lng) {
          mapConfig.center = [this.lng, this.lat]
        }
        this.map = new AMap.Map('js-container', mapConfig)
        const t = this
        // 加载地图搜索插件
        AMap.service('AMap.PlaceSearch', () => {
          this.placeSearch = new AMap.PlaceSearch({
            pageSize: 5,
            pageIndex: 1,
            citylimit: false,
            // city: '绵阳',
            map: t.map
            // panel: 'js-result'
          })
        })
        // 输入提示
        var autoOptions = {
          input: 'input'
        }
        var auto = new AMap.Autocomplete(autoOptions)
        AMap.event.addListener(auto, 'select', select)// 注册监听，当选中某条记录时会触发
        function select (e) {
          t.placeSearch.setCity(e.poi.adcode)
          t.placeSearch.search(e.poi.name) // 关键字查询查询
        }

        // 创建地图拖拽
        t.positionPicker = new PositionPicker({
          mode: 'dragMap', // 设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
          map: t.map // 依赖地图对象
        })
        // 拖拽完成发送自定义 drag 事件
        t.positionPicker.on('success', positionResult => {
          this.getFormAddress(positionResult)
          this.setPlace(positionResult)
          // 过滤掉初始化地图后的第一次默认拖放
          if (!this.dragStatus) {
            this.dragStatus = true
          } else {
            this.$emit('drag', positionResult)
          }
        })
        // 启动拖放
        this.positionPicker.start()
        this.map.on('complete', this.addOriginMarker(this.lng, this.lat))
      })
    },
    addOriginMarker (lng, lat) {
      // 地图图块加载完成后触发
      this.marker = new AMap.Marker({
        position: [lng, lat],
        image:
          '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png', // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        map: this.map
      })
      this.map.add(this.marker)
    },
    getFormAddress (positionResult) {
      // this.addressForm.address = fullAddress.substring(this.searchKey.length)
      this.addressForm.address = positionResult.address
      this.submitAddress = positionResult.address
      this.addressForm.coordinate.latitude = positionResult.position.lat
      this.addressForm.coordinate.longitude = positionResult.position.lng
      this.addressForm.cityCode = positionResult.regeocode.addressComponent.adcode
    },
    setPlace (positionResult) {
      this.place.address = positionResult.address
      this.place.lat = positionResult.position.lat
      this.place.lng = positionResult.position.lng
    }
  },
  mounted () {
    this.initMap()
  },
  created () {
  }
}
</script>

<style lang="css">
</style>
